package collection;

import java.util.HashSet;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * HashSet 底层用的是 HashMap
 *     public HashSet() {
 *         map = new HashMap<>();
 *     }
 *
 * CopyOnWriteArraySet 底层用的 CopyOnWriteArrayList
 * 运行放NULL进去
 * add方法添加的时候 如果不存在 返回true,如果已经存在返回false 表示添加失败
 * 底层是循环判断
 * @author jiangwz
 * @create 2019/9/14.
 */
public class TestCopyOnWriteArraySet {

    static CopyOnWriteArraySet copyOnWriteArraySet = new CopyOnWriteArraySet();
    static HashSet<String> set = new HashSet<>();

    public static void main(String[] args){
        /**
         * 不安全
         */
//        testHashSet();
        /**
         * 安全
         */
//        testCopyOnWriteArraySet();


        System.out.println(copyOnWriteArraySet.add(2));
        System.out.println(copyOnWriteArraySet.add(2));
        System.out.println(copyOnWriteArraySet.add(null));
        System.out.println(copyOnWriteArraySet);
    }

    private static void testHashSet() {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(set);
            }, "" + i).start();
        }
    }

    /**
     * 安全
     */
    private static void testCopyOnWriteArraySet() {
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                copyOnWriteArraySet.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(copyOnWriteArraySet);
            }, "" + i).start();
        }

    }
}
